"""
备注：
备注：
浏览器断点调试，不需要每次都要重新跑 类实现
"""
import os
from selenium import webdriver
# from selenium.webdriver.chrome.options import Options
import socket


# 单独打开浏览器，使用9222端口，信息保存到E:/pythonwork/testfile
# 请在这个浏览器下面安装xpath-help儿插件
class DebugBrowser:
    def __init__(self):
        options2 = webdriver.ChromeOptions()

        WIDTH = 600
        HEIGHT = 1280
        PIXEL_RATIO = 3.0
        UA = 'Mozilla/5.0 (Linux; Android 4.1.1; GT-N7100 Build/JRO03C) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/35.0.1916.138 Mobile Safari/537.36 T7/6.3'
        mobileEmulation = {"deviceMetrics": {"width": WIDTH, "height": HEIGHT, "pixelRatio": PIXEL_RATIO}, "userAgent": UA}
        # options2.add_experimental_option("mobileEmulation", mobileEmulation)        
        # options2.add_argument("--auto-open-devtools-for-tabs")

        self.ip = '127.0.0.1'
        self.port = 5003
        self.user_file = 'E:/Py_selenium/auto2/'
        self.chrome_option = options2

    def debug_chrome(self,proxy=False,port=False):
        """
        :return: chrome_option 浏览器调试选项
        """
        # self.chrome_option.add_argument('--proxy-server={0}'.format(proxy.proxy))

        port = self.port

        # if (False==port):
        #     port = self.port
        # else:
        #     self.port = port

        # port = 5003
        # 判断是否已经启动调试端口，已启动直接添加监听选项
        if self.check_port():
           self.chrome_option.add_experimental_option('debuggerAddress', '{}:{}'.format(self.ip, port))
        # 未启动则重新启动浏览器并监听调试端口
        else:
            os.popen('chrome.exe --remote-debugging-port="{}" --user-data-dir="{}"'.format(port, self.user_file))            
            self.chrome_option.add_experimental_option('debuggerAddress', '{}:{}'.format(self.ip,port))
        
        
        return self.chrome_option
         

    def check_port(self):
        """
        判断调试端口是否监听
        :return:check 是否监听
        """
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex((self.ip, self.port))
        if result == 0:
            check = True
        else:
            check = False
        sock.close()
        return check
  
#  使用方法
#  如果在该端口存在浏览器，直接使用该浏览器启动driver
#  如果不存在，则在端口打开浏览器，然后再在该端口启动driver
#if __name__ == '__main__':
